package org.redmagic.service.utils;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.redmagic.service.domain.Property;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public final class MongoUtils {
	
	private MongoUtils() {}
	
	public static DBObject getQuery(Property createOrUpdateProperty) {
		return getQuery(createOrUpdateProperty.getBase(), createOrUpdateProperty.getTags());
	}

	public static DBObject getQuery(String base, List<String> tags) {
		
		Collections.sort(tags);
		
		DBObject query = new BasicDBObject();
		query.put(MongoProperties.ID_BASE, base);
		query.put(MongoProperties.ID_TAGS, tags.toString());
		
		return query;
	}
	
	public static DBObject getAccessObject(String user) {
		
		DBObject odometer = new BasicDBObject(MongoProperties.ODOMETER_KEY, 1);
		DBObject lastAccess = new BasicDBObject()
		             .append(MongoProperties.ACCESSED_DATE_KEY, new Date())
		             .append(MongoProperties.ACCESSED_USER_KEY, user);
		
		DBObject update = new BasicDBObject()
		                   .append("$inc", odometer)
		                   .append("$set", lastAccess);
		return update;
	}

	public static DBObject getInsertObject(Property property, String user) {
		
		List<String> tags = property.getTags();
		Collections.sort(tags);
		
		DBObject id = new BasicDBObject(MongoProperties.BASE, property.getBase());
		id.put(MongoProperties.TAGS_KEY, tags.toString());
		DBObject insert = new BasicDBObject(MongoProperties.ID, id);
		insert.put(MongoProperties.VALUE_KEY, property.getValue());
		insert.put(MongoProperties.ODOMETER_KEY, 0);
		insert.put(MongoProperties.CREATION_DATE_KEY, new Date());
		insert.put(MongoProperties.CREATION_USER_KEY, user);
		insert.put(MongoProperties.MODIFIED_DATE_KEY, new Date());
		insert.put(MongoProperties.MODIFIED_USER_KEY, user);
		
		return insert;
	}

	public static DBObject getUpdateObject(Property property, String user) {

		DBObject updated = new BasicDBObject()
		           .append(MongoProperties.VALUE_KEY, property.getValue())
		           .append(MongoProperties.MODIFIED_DATE_KEY, new Date())
		           .append(MongoProperties.MODIFIED_USER_KEY, user);
		
		DBObject dbObject = new BasicDBObject("$set", updated);
		
		return dbObject;
	}
}
